package src;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;


public final class Nodelist {
	
	private static ArrayList<Node> nodes;
	
	public Nodelist() throws UnknownHostException {
		nodes = new ArrayList<Node>();
	      try{
	    	  
	    	    // Open the file that is the first 
	    	    // command line parameter
	    	    FileInputStream fstream = new FileInputStream("config.txt");
	    	    // Get the object of DataInputStream
	    	    DataInputStream in = new DataInputStream(fstream);
	    	    BufferedReader br = new BufferedReader(new InputStreamReader(in));
	    	    String strLine;
	    	    //Read File Line By Line
	    	    while ((strLine = br.readLine()) != null)   {
	    	      int id = Integer.parseInt(strLine.substring(0, strLine.indexOf(" ")));
	    	      String hostname = strLine.substring(strLine.indexOf(" ")+1);
	    	      InetAddress add = InetAddress.getByName(hostname);
	    	      Node n = new Node(add, id, hostname);
	    	      nodes.add(n);
	    	
	    	    }

	    	    //Close the input stream
	    	    in.close();
	    	    }catch (Exception e){//Catch exception if any
	    	      System.err.println("Error: " + e.getMessage());
	    	    }
	    	 
	}
	public static Node getNode(int id) {
		return nodes.get(id+1);
	}
	
	public static int getIntFromAddress(InetAddress sender) {
		for(int i=0; i < nodes.size(); i++) {
			if (nodes.get(i).getAddress().equals(sender)) {
				return nodes.get(i).getId();
			}
		}
		return -1;
	}
	
	public static ArrayList<Node> getNodes() {
		return nodes;
	}
	
	
}
